import express from "express";
import MySQLPool from '../mysqlCreatePool';
import { host } from "../server.config";
import { upload } from "../uploadFile";
import { getuserinfo } from "../sqlstring";
const router = express.Router();
const db = new MySQLPool();
// 获取用户信息
router.get("/info", async (req: any, res) => {
  const id = req.auth.id ?? ""
  await getuserinfobyid(id, res)
});
// 获取关系用户信息
router.get("/linkinfo", async (req: any, res) => {
  const id = req.query.id ?? ""
  await getuserinfobyid(id, res)
});

// 获取关系用户信息
router.get("/getmmb", async (req: any, res) => {
  const id = req.auth.id ?? ""
  const sql = ` SELECT CONVERT(COALESCE(asum,0),UNSIGNED) AS asum,CONVERT(COALESCE(smmb,0),UNSIGNED) AS smmb,CONVERT(COALESCE(asum,0)-COALESCE(smmb,0),UNSIGNED) AS mmb
  FROM (SELECT t.user_id,SUM(t.num*b.num) AS asum FROM todo AS t,bonus as b WHERE t.bonus_id=b.id GROUP BY t.user_id) AS tb
  LEFT JOIN (SELECT e.user_id,SUM(r.num) AS smmb FROM reward AS r,exchange AS e WHERE r.id=e.reward_id GROUP BY e.user_id) AS re
  ON re.user_id=tb.user_id
  WHERE re.user_id=${id}`;
  try {
    const [sqlres] = await db.queryRows(sql)
    if (sqlres && sqlres[0]) {
      const mmb = sqlres[0]
      res.send({
        code: 200,
        message: '',
        data: mmb,
      });
    }
    else {
      res.send({
        code: 201,
        message: '没数据',
        data: null,
      });
    }
  } catch (e) {
    res.send({
      code: 201,
      message: e,
      data: null,
    });
  }
});

// 修改用户信息
router.post('/update', upload.single('avatar'), async (req: any, res) => {
  const { id } = req.auth
  const userinfo = { ...req.body }
  let sql = 'update user_info set '
  if (req.file && !userinfo.avatar?.includes(host)) {
    userinfo.avatar = req.file?.filename ? '/uploads/' + req.file?.filename : null
    sql += `avatar='${userinfo.avatar}',`
  }
  sql += `nickname='${userinfo.nickname}',gender=${userinfo.gender},birthday='${userinfo.birthday}',role=${userinfo.role} where id=${id}`;
  try {
    const [sqlres] = await db.executeResult(sql)
    if (sqlres.changedRows) {
      res.send({
        code: 200,
        message: '',
        data: userinfo,
      });
    } else {
      res.send({
        code: 201,
        message: '修改失败',
        data: null,
      });
    }
  }
  catch (e) {
    res.send({
      code: 201,
      message: e,
      data: null,
    });
  }
})

// 生成关系码
router.post('/linkCode', async (req: any, res) => {
  const { id } = req.auth
  try {
    const data = getShareToken(8)
    const sql = `UPDATE user_info SET link_code='${data}' WHERE id=${id};`
    const [sqlres] = await db.queryResults(sql)
    if (sqlres && sqlres.affectedRows) {
      res.send({
        code: 200,
        message: '',
        data,
      });
    }
    else {
      res.send({
        code: 201,
        message: '生成失败',
        data: null
      })
    }
  } catch (e) {
    res.send({
      code: 201,
      message: e,
      data: null
    })
  }
})

// 绑定关系
router.post('/bindLink', async (req: any, res) => {
  const { id, role } = req.auth
  const { linkCode } = req.body
  console.log(linkCode)
  try {
    const sql = `CALL BindLink(${id},${role},'${linkCode}');`
    const [sqlres] = await db.executeRowsAsArray(sql)
    const resData = {
      code: 201,
      message: "",
      data: null
    }
    switch (sqlres[0][0].link_id) {
      case 0:
        resData.message = '已绑定过了'
        break;
      case -1:
        resData.message = '不能绑定自己'
        break;
      case -2:
        resData.message = '无效关系码'
        break;
      case -3:
        resData.message = '确认双方身份无误'
        break;
      default:
        resData.code = 200
        resData.data = sqlres[0][0]
        break;
    }
    res.send(resData)
  } catch (e) {
    res.send({
      code: 201,
      message: e,
      data: null
    })
  }
})

function getShareToken(length: number) {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let shareToken = '';
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    const randomChar = characters.charAt(randomIndex);
    shareToken += randomChar;
  }
  return shareToken;
}

async function getuserinfobyid(id: number, res: any) {
  const sql = getuserinfo(`id=${id}`);
  try {
    const [sqlres] = await db.queryRows(sql)
    if (sqlres && sqlres[0]) {
      const user = sqlres[0]
      delete user.openid
      res.send({
        code: 200,
        message: '',
        data: user,
      });
    }
    else {
      res.send({
        code: 201,
        message: '没数据',
        data: null,
      });
    }
  } catch (e) {
    console.log(e)
    res.send({
      code: 201,
      message: e,
      data: null,
    });
  }
}
export default router
